package dLogistic.domain.model.Magazyn;

import dLogistic.infrastructure.persistence.hibernate.HibernateRepository;
import dLogistic.infrastructure.persistence.hibernate.HibernateUtil;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.util.List;

/**
 * Created by Przemek on 2014-10-24.
 */
public class MagazynRepository extends HibernateRepository {
    private static SessionFactory factory;

    public void zapisz(MagazynAggr magazyn) {
        try{
            factory = new Configuration().configure("/resources/hibernate.cfg.xml").buildSessionFactory();
        }catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        Session session = factory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        session.saveOrUpdate(magazyn);

        transaction.commit();
    }


    public JSONArray zwrocListAll(){
        factory = HibernateUtil.getSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction transaction = session.beginTransaction();

        String sql = "select * from Magazyn";
        SQLQuery query = session.createSQLQuery(sql);
        query.addEntity(MagazynAggr.class);

        List results = query.list();
        transaction.rollback();
        JSONArray ja = new JSONArray();
        for (Integer i = 0; i < results.size(); i++) {
            MagazynAggr magazynAggr = (MagazynAggr) results.get(i);
            JSONObject obj = new JSONObject();
            obj.put("uuid", magazynAggr.uuid());
            obj.put("nazwa", magazynAggr.nazwa());
            ja.add(obj);
        }
        return ja;
    }

    public MagazynAggr znajdz(String uuid){
        factory = HibernateUtil.getSessionFactory();
        Session session = factory.getCurrentSession();

        Transaction transaction = session.beginTransaction();
        String sql = "select * from Magazyn where uuid = :uuid";
        SQLQuery query = session.createSQLQuery(sql);
        query.addEntity(MagazynAggr.class);
        query.setParameter("uuid", uuid);
        List results = query.list();
        transaction.rollback();
        if (!results.isEmpty()){
            return (MagazynAggr) results.get(0);
        }
        else {
            return null;
        }

    }




}
